package com.dsh.gulimall.product.web;

import com.dsh.gulimall.product.entity.CategoryEntity;
import com.dsh.gulimall.product.service.CategoryService;
import com.dsh.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class indexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate redisTemplate;


    @GetMapping(value = {"/","index.html"})
    private String indexPage(Model model) {

        //1、查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categories",categoryEntities);

        return "index";
    }


    @ResponseBody
    @GetMapping("index/catalog.json")
    public Map<String,  List<Catelog2Vo>> getCatalogJson() {

        Map<String,  List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }


    @ResponseBody
    @GetMapping("hello")
    public String hello(){

        //1.获取一把锁，只要锁的名字一样就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //2.加锁
        lock.lock( 10,TimeUnit.SECONDS);  //堵塞式等待
        try{
            System.out.println("加锁成功" +Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){

        }finally {
            //3.解锁
            System.out.println("解锁成功" +Thread.currentThread().getId());
            lock.unlock( );
        }
        return "hello";
    }


    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        String s = "";
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.writeLock();
        try {
            //改数据加写锁，读数据加加写锁

            rLock.lock();
            Thread.sleep(30000);
            s = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set("writeValue",s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }


    /**
     * 保证一定等读取到最新数据
     * @return
     */
    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        String s = "";
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();
        //加读锁
        rLock.lock();
        try {
            s = redisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }



    /**
     * 放假，锁门
     * 1班没人l
     * 5个班级全部走完，我们可以锁大门
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        // 锁的名字
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();//等待闭锁都完成
        return "放假了";
    }

    @GetMapping("/gogo/{id}")
    @ResponseBody
    public String gogo(@PathVariable("id") Long id){
        RCountDownLatch door = redisson.getCountDownLatch("door");
        //计数-1
        door.countDown();
        return id +"全部走完了";
    }


    /**
     * 停车位
     * @return
     * @throws InterruptedException
     *
     * 信号 可以作为分布式的限流
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        // 信号量的名字
        RSemaphore park = redisson.getSemaphore("park");
        //获取一个信号，获取哦一个值，占一个车位
        // 带 tay 都不杜塞
        boolean b = park.tryAcquire();
        if (b){
            //执行业务
        }else {
            return "当前位置为空";
        }
        return "ok--->" + b;
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        // 信号量的名字
        RSemaphore park = redisson.getSemaphore("park");
        // 释放一个车位
        park.release();
        return  "ok";
    }

}
